package com.water.control;

import android.Manifest;
import android.app.Activity;
import android.app.AlertDialog;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.water.control.adapter.DevicesAdapter;
import com.water.control.util.ToastUtil;

import java.util.ArrayList;
import java.util.List;

public class DeviceList2Activity extends Activity implements View.OnClickListener {
    private final int REQUEST_ENABLE_BT = 0xa01;
    private final int PERMISSION_REQUEST_COARSE_LOCATION = 0xb01;

    private String TAG = DeviceList2Activity.class.getSimpleName();

    private final List<BluetoothDevice> devices = new ArrayList<>();

    private DevicesAdapter mAdapter;
    private BluetoothAdapter mBluetoothAdapter;

    private TextView mTvMessage;
    private boolean isSannering;

    public static void start(Context context) {
        Intent starter = new Intent(context, DeviceList2Activity.class);
        context.startActivity(starter);
    }

    /**
     * 广播接收发现蓝牙设备
     */
    private BroadcastReceiver mReceiver = new BroadcastReceiver() {

        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();

            if (BluetoothAdapter.ACTION_DISCOVERY_STARTED.equals(action)) {
                mTvMessage.setText("正在扫描...");
                isSannering = true;
            }

            if (BluetoothDevice.ACTION_FOUND.equals(action)) {
                BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
                if (device != null) {
                    // 添加到ListView的Adapter。
                    devices.add(device);
                    mAdapter.notifyDataSetChanged();
                }
            }

            if (BluetoothAdapter.ACTION_DISCOVERY_FINISHED.equals(action)) {
                mTvMessage.setText("扫描结束.");
                isSannering = false;
            }
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_devices2);

        TextView tvTopTitleCenter = findViewById(R.id.tvTopTitleCenter);
        tvTopTitleCenter.setText("设备列表");
        mTvMessage = findViewById(R.id.tv_msg);
        ListView listView = findViewById(R.id.listView);
        findViewById(R.id.tvTopTitleLeft).setOnClickListener(this);
        findViewById(R.id.init).setOnClickListener(this);
        findViewById(R.id.discovery).setOnClickListener(this);
        findViewById(R.id.enable_discovery).setOnClickListener(this);
        findViewById(R.id.tv_refresh).setOnClickListener(this);

        // 注册广播接收器。
        // 接收蓝牙发现
        IntentFilter filterFound = new IntentFilter(BluetoothDevice.ACTION_FOUND);
        registerReceiver(mReceiver, filterFound);

        IntentFilter filterStart = new IntentFilter(BluetoothAdapter.ACTION_DISCOVERY_STARTED);
        registerReceiver(mReceiver, filterStart);

        IntentFilter filterFinish = new IntentFilter(BluetoothAdapter.ACTION_DISCOVERY_FINISHED);
        registerReceiver(mReceiver, filterFinish);

        mAdapter = new DevicesAdapter(this, devices);
        mAdapter.setOnConnectClickListener(new DevicesAdapter.OnConnectClickListener() {
            @Override
            public void onConnectClick(int position) {
                Bundle b = new Bundle();
                b.putString(BluetoothDevice.EXTRA_DEVICE, devices.get(position).getAddress());

                Intent result = new Intent();
                result.putExtras(b);
                setResult(Activity.RESULT_OK, result);
                finish();
            }
        });
        listView.setAdapter(mAdapter);

        onRefresh();
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.tvTopTitleLeft:
                onBackPressed();
                break;
            case R.id.init:
                init();
                break;
            case R.id.discovery:
                discovery();
                break;
            case R.id.enable_discovery:
                enable_discovery();
                break;
            case R.id.tv_refresh:
                onRefresh();
                break;
            default:
                break;
        }
    }

    private void onRefresh() {
        if (!isSannering) {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                if (checkSelfPermission(Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED
                        && checkSelfPermission(Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
                    requestPermissions(new String[]{Manifest.permission.ACCESS_COARSE_LOCATION,
                            Manifest.permission.ACCESS_FINE_LOCATION}, PERMISSION_REQUEST_COARSE_LOCATION);
                } else {
                    devices.clear();
                    mAdapter.notifyDataSetChanged();
                    discovery();
                }
            } else {
                devices.clear();
                mAdapter.notifyDataSetChanged();
                discovery();
            }
        } else {
            ToastUtil.show("当前正在扫描...");
        }
    }

    // 初始化蓝牙设备
    private void init() {
        mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();

        // 检查设备是否支持蓝牙设备
        if (mBluetoothAdapter == null) {
            showMessage("设备不支持蓝牙");
            mTvMessage.setText("设备不支持蓝牙");

            // 不支持蓝牙，退出。
            return;
        }

        // 如果用户的设备没有开启蓝牙，则弹出开启蓝牙设备的对话框，让用户开启蓝牙
        if (!mBluetoothAdapter.isEnabled()) {
            showMessage("请求用户打开蓝牙");
            mTvMessage.setText("请求用户打开蓝牙");

            Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
            startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT);
            // 接下去，在onActivityResult回调判断

        }
        //设置自身也可以死被发现
//        enable_discovery();
    }

    // 启动蓝牙发现...
    private void discovery() {
        if (mBluetoothAdapter == null) {
            init();
        }

        mBluetoothAdapter.startDiscovery();
    }

    // 可选方法，非必需
    // 此方法使自身的蓝牙设备可以被其他蓝牙设备扫描到，
    // 注意时间阈值。0 - 3600 秒。
    // 通常设置时间为120秒。
    private void enable_discovery() {
        Intent discoverableIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);

        // 第二个参数可设置的范围是0~3600秒，在此时间区间（窗口期）内可被发现
        // 任何不在此区间的值都将被自动设置成120秒。
        discoverableIntent.putExtra(BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION, 3600);

        startActivity(discoverableIntent);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if (requestCode == REQUEST_ENABLE_BT) {
            if (resultCode == RESULT_OK) {
                Log.d(TAG, "打开蓝牙成功！");
                mTvMessage.setText("打开蓝牙成功！");
                discovery();
            }
            if (resultCode == RESULT_CANCELED) {
                Log.d(TAG, "放弃打开蓝牙！");
                mTvMessage.setText("放弃打开蓝牙！");
            }
        } else {
            mTvMessage.setText("蓝牙异常！");
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) {
        switch (requestCode) {
            case PERMISSION_REQUEST_COARSE_LOCATION:
                if (grantResults[0] == PackageManager.PERMISSION_GRANTED
                        && grantResults[1] == PackageManager.PERMISSION_GRANTED) {
                    onRefresh();
                }
                break;
            default:
                break;
        }
    }

    public void showMessage(String msg) {
        Toast.makeText(this, msg, Toast.LENGTH_SHORT).show();
    }

    @Override
    public void onBackPressed() {
        if (isSannering) {
            new AlertDialog.Builder(this).setTitle("提示")
                    .setMessage("当前正在扫描蓝牙设备，是否退出？")
                    .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialogInterface, int i) {
                            finish();
                        }
                    })
                    .setNegativeButton("取消", null).show();
        } else {
            super.onBackPressed();
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        unregisterReceiver(mReceiver);
    }
}
